/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.bus.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.thinkgem.jeesite.common.persistence.ResponseResult;
import com.thinkgem.jeesite.common.utils.EnumProperty;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.bus.dao.AuditDao;
import com.thinkgem.jeesite.modules.bus.entity.*;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Attachment;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.AttachmentService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.bus.dao.VaccineDao;

/**
 * 疫苗补助Service
 * @author zhangxingliang
 * @version 2019-06-10
 */
@Service
@Transactional(readOnly = true)
public class VaccineService extends CrudService<VaccineDao, Vaccine> {

	@Lazy
	@Autowired
	private AuditService auditService;
	@Autowired
	private VaccineInfoService vaccineInfoService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private VaccineDao vaccineDao;
	@Autowired
	private AuditDao auditDao;
	@Autowired
	private EntService entService;

	public Vaccine get(String id) {
		return super.get(id);
	}


	public List<Vaccine> findList(Vaccine vaccine) {
		return super.findList(vaccine);
	}
	
	public Page<Vaccine> findPage(Page<Vaccine> page, Vaccine vaccine) {
		return super.findPage(page, vaccine);
	}
	
	@Transactional(readOnly = false)
	public void save(Vaccine vaccine) {
		super.save(vaccine);
	}
	
	@Transactional(readOnly = false)
	public void delete(Vaccine vaccine) {
		//delete vaccine ,attachment ,vaccineInfo

		super.delete(vaccine);
	}

	/**
	 *
	 * @Title: provinceRejectList
	 * @author: sy
	 * @date: 2019年06月11日 9:25
	 * @Description: 省级驳回记录列表
	 * @param page
	 * @param vaccine
	 * @return: com.thinkgem.jeesite.common.persistence.Page<com.thinkgem.jeesite.modules.bus.entity.Vaccine>
	 */
    public Page<Vaccine> provinceRejectList(Page<Vaccine> page, Vaccine vaccine) {
		vaccine.setPage(page);
		if(StringUtils.isBlank(vaccine.getAreaCode())){
			Area area = UserUtils.getUser().getOffice().getArea();
			if(null != area){
				String areaCode = area.getCode();
				vaccine.setAreaCode(areaCode);
			}
		}
		List<Vaccine> list = dao.provinceRejectList(vaccine);
		page.setList(list);
		return page;
    }

    /**
     *
     * @Title: provinceVaccineList
     * @author: sy
     * @date: 2019年06月11日 16:36
     * @Description: 省级补助记录
     * @param page
     * @param vaccine
     * @return: com.thinkgem.jeesite.common.persistence.Page<com.thinkgem.jeesite.modules.bus.entity.Vaccine>
     */
    public Page<Vaccine> provinceVaccineList(Page<Vaccine> page, Vaccine vaccine) {
		vaccine.setPage(page);
		List<Vaccine> list = dao.provinceVaccineList(vaccine);
		page.setList(list);
		return page;
    }

    /**
     *
     * @Title: provinceReject
     * @author: sy
     * @date: 2019年06月11日 19:40
     * @Description: 省级一键驳回
     * @param vaccine
     * @return: void
     */
	@Transactional(readOnly = false)
	public void provinceReject(Vaccine vaccine) {
		vaccine.setAuditStatus(EnumProperty.AuditTypeEnum.PROVINCEREJECT.getKey());
		vaccine.preUpdate();
		dao.update(vaccine);
		//update by ZYJ
		String auditId = vaccine.getAuditId();
		Audit audit = auditService.get(auditId);
		audit.setAuditDate(new Date());
		audit.setAuditOpinion(vaccine.getAudit().getAuditOpinion());
		audit.setNoticeStatus(Integer.parseInt(EnumProperty.DataStatus.UNREADNOTICE.getKey()));
		audit.setAuditStatus(EnumProperty.AuditTypeEnum.PROVINCEREJECT.getKey());
		auditService.save(audit);
		//end ZYJ
		
//		Audit audit = vaccine.getAudit();
//		audit.setTableId(vaccine.getId());
//		audit.setUserId(vaccine.getEntId());
//		audit.setTableName("bus_vaccine");
//		audit.setAuditDate(new Date());
//		audit.setAuditStatus(EnumProperty.AuditTypeEnum.PROVINCEREJECT.getKey());
//		audit.setNoticeStatus(Integer.parseInt(EnumProperty.DataStatus.UNREADNOTICE.getKey()));
//		audit.setSubmitDate(vaccine.getSubmitDate());
//		auditService.save(audit);
	}
	
	/**
	 * @Author zhangxingliang
	 * @Description  编辑疫苗补助信息
	 * @Date 11:46 2019/6/12
	 **/
	@Transactional(readOnly = false)
	public void edit(Vaccine vaccine) {
		User user = UserUtils.getUser();
		if (StringUtils.isBlank(user.getId())
				|| StringUtils.isBlank(vaccine.getAuditStatus())
				|| (!EnumProperty.AuditTypeEnum.AWAITREVIEWED.getKey().equals(vaccine.getAuditStatus())
				&& !EnumProperty.AuditTypeEnum.UNREVIEWED.getKey().equals(vaccine.getAuditStatus()))
		) {
			return;
		}
		Ent ent = this.entService.get(user.getId());
		vaccine.setEntId(ent.getId());
		vaccine.setEntHistoryId(ent.getEntHistoryId());

		if ((StringUtils.isBlank(vaccine.getId()) || "-1".equals(vaccine.getId()))
			|| (null != vaccine.getAudit() && StringUtils.isNotBlank(vaccine.getAudit().getAuditStatus()))
			&& (EnumProperty.AuditTypeEnum.REJECT.getKey().equals(vaccine.getAudit().getAuditStatus())
			|| EnumProperty.AuditTypeEnum.PROVINCEREJECT.getKey().equals(vaccine.getAudit().getAuditStatus()))
		) {
			if(StringUtils.isNotBlank(vaccine.getId())){
				this.dao.deleteAppVaccine(vaccine.getId());
			}
			vaccine.setId(IdGen.nextId());
			vaccine.setIsNewRecord(true);
		}
		vaccine.setSubmitDate(new Date());
		vaccine.setStatus(EnumProperty.DataStatus.ABLE.getKey());
		//提交审核
		if (EnumProperty.AuditTypeEnum.UNREVIEWED.getKey().equals(vaccine.getAuditStatus())) {
			this.auditService.save(new Audit(IdGen.nextId(),vaccine.getId(),"bus_vaccine",user.getId(),vaccine.getEntHistoryId(),true));
		}
		//处理疫苗详情信息保存和删除
		this.vaccineInfoService.save(vaccine.getVaccineInfoList(),vaccine.getId(),vaccine.getEntId(),vaccine.getEntHistoryId(),vaccine.getIsNewRecord());
		//处理附件保存和删除
		this.attachmentService.save(vaccine.getAttachmentList(),vaccine.getId(),"bus_vaccine",vaccine.getIsNewRecord());

		super.save(vaccine);
	}

	/**
	 * @author Zhang Xingliang
	 * @description 疫苗补助列表页直接提交待审
	 * @date 20:16 2019/6/22
	 * @params [vaccine]
	 * @return void
	 **/
	@Transactional(readOnly = false)
	public ResponseResult update(Vaccine vaccine) {
		try {
			vaccine = this.get(vaccine.getId());

			/*
			Integer fileCnt = this.attachmentService.findAttachmentCnt(new Attachment(vaccine.getId(), "bus_vaccine","record"));
			//0：未传附件 , 1：传记录照片
			if (0 == fileCnt) {
				return ResponseResult.success(fileCnt);
			}
			*/
			User user = UserUtils.getUser();
			Ent ent = this.entService.get(user.getId());
			this.auditService.save(new Audit(IdGen.nextId(), vaccine.getId(), "bus_vaccine", user.getId(), vaccine.getEntHistoryId(), true));
			vaccine.setSubmitDate(new Date());
			vaccine.setAuditStatus(EnumProperty.AuditTypeEnum.UNREVIEWED.getKey());
			vaccine.setEntId(ent.getId());
			vaccine.setEntHistoryId(ent.getEntHistoryId());
			vaccine.setStatus(EnumProperty.DataStatus.ABLE.getKey());
			super.save(vaccine);
			return ResponseResult.success(1);
		} catch (Exception e) {
			return ResponseResult.failure("编辑失败，错误如下：" + e.getMessage());
		}
	}

	/**
	 * @author zhangxingliang
	 * @description app 端删除已驳回数据，pc端需要留存数据
	 * @date 11:09 2019/6/21
	 * @params [id]
	 * @return com.thinkgem.jeesite.common.persistence.ResponseResult
	 **/
	@Transactional(readOnly = false)
	public ResponseResult deleteVaccine(Vaccine vaccine) {
		if( null!= vaccine && StringUtils.isNotBlank(vaccine.getAuditStatus())
		){
			if( EnumProperty.AuditTypeEnum.REJECT.getKey().equals(vaccine.getAuditStatus())
					|| EnumProperty.AuditTypeEnum.PROVINCEREJECT.getKey().equals(vaccine.getAuditStatus())){
				vaccine.setStatus(EnumProperty.DataStatus.UNABLE.getKey());
//				vaccine.preUpdate();
				dao.deleteAppVaccine(vaccine.getId());
				return ResponseResult.success();
			}else if (EnumProperty.AuditTypeEnum.AWAITREVIEWED.getKey().equals(vaccine.getAuditStatus())){
				vaccine.setStatus(EnumProperty.DataStatus.UNABLE.getKey());
				vaccine.preUpdate();
				//delete vaccine ,attachment ,vaccineInfo
				this.delete(vaccine);
				return ResponseResult.success();
			}
		}
		return ResponseResult.failure("no power");
	}


	/**
	 *
	 * @Title: vaccineView
	 * @author: sy
	 * @date: 2019年06月13日 9:17
	 * @Description: 疫苗补助查看
	 * @param vaccine
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
	public Vaccine vaccineView(Vaccine vaccine) {
		Vaccine queryVaccine = dao.findVaccineBasic(vaccine);
		VaccineInfo vaccineInfo = new VaccineInfo();
		vaccineInfo.setVaccineId(vaccine.getId());
		//子表List
		List<VaccineInfo> vaccineInfoList = vaccineInfoService.findList(vaccineInfo);
		if (vaccineInfoList.size()>0){
			queryVaccine.setVaccineInfoList(vaccineInfoList);
		}
		//审核表
		Audit audit = auditService.findNewestAuditByTblId(vaccine.getId(),"bus_vaccine");
		queryVaccine.setAudit(audit);
		return queryVaccine;
	}
	/**
	 *
	 * @Title: uncheckedList
	 * @author: mengying
	 * @date: 2019年06月13日 15:17
	 * @Description: 补助审核页
	 * @param vaccine
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
	public Page<Vaccine> vaccineUncheckedList(Page<Vaccine> page,Vaccine vaccine,String statusFlag) {
		User user = UserUtils.getUser();
		String areaCode = user.getOffice().getCode();
		vaccine.setAreaCode(areaCode);
		vaccine.setPage(page);
		if(statusFlag.equals(EnumProperty.AuditTypeEnum.UNREVIEWED.getKey())){
			page.setList(vaccineDao.vaccineUncheckedList(vaccine));
		}
		if(statusFlag.equals(EnumProperty.AuditTypeEnum.REVIEWED.getKey())){
			page.setList(vaccineDao.vaccineCheckedList(vaccine));
		}
		if(statusFlag.equals(EnumProperty.AuditTypeEnum.SUCCESS.getKey())){
			page.setList(vaccineDao.vaccineRecord(vaccine));
		}
		return page;
	}
	/**
	 *
	 * @Title: updateVaccineStatus
	 * @author: mengying
	 * @date: 2019年06月14日 15:17
	 * @Description: 补助改变审核状态
	 * @return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	 */
	@Transactional(readOnly = false)
	public boolean updateVaccineStatus(String auditId,String updateFlag,String auditOpinion,String id){
		if(StringUtils.isNotEmpty(auditId)&&StringUtils.isNotEmpty(updateFlag)){
			if (EnumProperty.AuditTypeEnum.SUCCESS.getKey().equals(updateFlag)){
				auditDao.changeAuditStatus(auditId,"",EnumProperty.AuditTypeEnum.SUCCESS.getKey(),auditOpinion,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),"bus_vaccine");
				vaccineDao.updateVaccineStatus(id,EnumProperty.AuditTypeEnum.SUCCESS.getKey(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				return true;
			}
			if(EnumProperty.AuditTypeEnum.REJECT.getKey().equals(updateFlag)){
				auditDao.changeAuditStatus(auditId,"",EnumProperty.AuditTypeEnum.REJECT.getKey(),auditOpinion,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),"bus_vaccine");
				vaccineDao.updateVaccineStatus(id,EnumProperty.AuditTypeEnum.REJECT.getKey(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				return true;
			}
		}
		return false;
	}

	/**
	 * @Author zhangxingliang
	 * @Description app 端获取疫苗补助列表
	 * @Date 9:44 2019/6/18
	 **/
	public Page<Vaccine> appVaccineList(Page<Vaccine> page, Vaccine vaccine) {
		vaccine.setPage(page);
		page.setList(dao.appVaccineList(vaccine));
		return page;
	}

	/**
	 * @Author zhangxingliang
	 * @Description 获取疫苗补助信息及审核状态
	 * @Date 10:24 2019/6/19
	 **/
	public Vaccine getInfoAndAudit(String id) {return this.vaccineDao.getInfoAndAudit(id);}

	/**
	 * @author Zhang Xingliang
	 * @description 疫苗补助发票唯一校验
	 * @date 17:14 2019/7/24 0024
	 * @param invoiceNo
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public Integer checkInvoice(String invoiceNo) {return this.vaccineDao.checkInvoice(invoiceNo);}

	/**
	 *@Title:checkInvoiceUpdate
	 *@Author: zyj
	 *@Date: 2019/8/11 17:06
	 *@Description: 发票验真修改发票状态
	 *@Param: [vaccine]
	 *@Return: void
	 */
    @Transactional(readOnly = false)
	public void checkInvoiceUpdate(Vaccine vaccine){
		dao.checkInvoiceUpdate(vaccine);
	}

	/**
	*@Title:findVaccine
	*@Author: zyj
	*@Date: 2019/8/12 15:02
	*@Description: 根据id查找
	*@Param: [vaccine]
	*@Return: com.thinkgem.jeesite.modules.bus.entity.Vaccine
	*/
	public Vaccine findVaccine(Vaccine vaccine){
		return dao.get(vaccine.getId());
	}
}